package com.rosense.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringWriter;

import com.rosense.client.rpc.RPCBean;
import com.rosense.client.rpc.RPCNetBean;

/**
 * 采集网络带宽使用率 
 * @author 李岩飞
 * @email eliyanfei@126.com	
 * 2018年1月23日 下午1:49:21
 * 
 */
public class NetUsage extends ResourceUsage {

	private static NetUsage INSTANCE = new NetUsage();

	private NetUsage() {
	}

	public static NetUsage getInstance() {
		return INSTANCE;
	}

	/** 
	 * @Purpose:采集网络带宽使用率 
	 * @param args 
	 * @return float,网络带宽使用率,小于1 
	 */
	@Override
	public RPCBean scan() {
		Process pro1;
		Runtime r = Runtime.getRuntime();
		RPCNetBean rpc = new RPCNetBean();
		try {
			String command = "sar -n DEV 1 1";
			//第一次采集流量数据  
			pro1 = r.exec(command);
			BufferedReader in1 = new BufferedReader(new InputStreamReader(pro1.getInputStream()));
			String line = null;
			float rx = 0, tx = 0;
			while ((line = in1.readLine()) != null) {
				line = line.trim();
				if (line.contains(":")) {
					String[] temp = line.split("\\s+");
					if (temp[1].startsWith("eth")) {
						rx = Float.parseFloat(temp[4]) / 1024; //单位为M  
						tx = Float.parseFloat(temp[5]) / 1024; //单位为M  
						if (rx != 0) {
							break;
						}
					}
				}
			}
			rpc.tx = tx;
			rpc.rx = rx;
			in1.close();
			pro1.destroy();
		} catch (IOException e) {
			StringWriter sw = new StringWriter();
			e.printStackTrace(new PrintWriter(sw));
		}
		return rpc;
	}

}